<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="姓名" prop="empName">
        <el-input
          v-model="queryParams.empName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="部门" prop="deptName">
        <el-select
          v-model="queryParams.deptName"
          placeholder="请选择部门"
          clearable
        >
          <el-option
            v-for="dict in sys_dept_list"
            :key="dict.deptId"
            :label="dict.deptName"
            :value="dict.deptName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入电话"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['employeeManagement:employeeManagement:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['employeeManagement:employeeManagement:edit']">修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['employeeManagement:employeeManagement:remove']"
          >删除</el-button
        >
      </el-col>
      <!-- 添加导入按钮 -->
      <!-- 在操作按钮区域添加导入按钮 -->
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['employee:employee:import']"
          >导入</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['employeeManagement:employeeManagement:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="employeeManagementList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- 添加序号列 -->
      <el-table-column label="序号" align="center" width="55">
        <template #default="scope">
          {{ rowIndex(scope.$index) }}
        </template>
      </el-table-column>

      <el-table-column label="员工编号" align="center" prop="empNo" />
      <el-table-column label="姓名" align="center" prop="empName" />
      <el-table-column label="性别" align="center" prop="gender">
        <template #default="scope">
          {{ formatGender(scope.row.gender) }}
        </template>
      </el-table-column>
      <el-table-column label="部门" align="center">
        <template #default="scope">
          {{ getDeptNameById(scope.row.deptId) || scope.row.deptName || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="电话" align="center" prop="phone" />
      <el-table-column label="邮箱" align="center" prop="email" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['employeeManagement:employeeManagement:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['employeeManagement:employeeManagement:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改培训人员管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="employeeManagementRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="员工编号" prop="empNo">
          <el-input v-model="form.empNo" placeholder="请输入员工编号" />
        </el-form-item>
        <el-form-item label="姓名" prop="empName">
          <el-input v-model="form.empName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择性别">
            <el-option
              v-for="dict in sys_user_sex.filter(
                (item) => item.label !== '未知'
              )"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="deptName">
          <el-select v-model="form.deptName" placeholder="请选择部门">
            <el-option
              v-for="dept in deptOptions"
              :key="dept.deptId"
              :label="dept.deptName"
              :value="dept.deptName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 导入对话框 -->
    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EmployeeManagement">
import {
  listEmployeeManagement,
  getEmployeeManagement,
  delEmployeeManagement,
  addEmployeeManagement,
  updateEmployeeManagement,
  importTemplate as downloadImportTemplate,
} from "@/api/employeeManagement/employeeManagement";
import { getToken } from "@/utils/auth";
import { listDept } from "@/api/system/dept";
const { proxy } = getCurrentInstance();
const { sys_user_sex } = proxy.useDict("sys_user_sex");
const rowIndex = computed(() => {
  return (index) =>
    (queryParams.value.pageNum - 1) * queryParams.value.pageSize + index + 1;
});

const employeeManagementList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const deptOptions = ref([]);
const sys_dept_list = ref([]);

// 添加上传相关的响应式数据
const upload = reactive({
  open: false,
  title: "",
  isUploading: false,
  updateSupport: false,
  headers: { Authorization: "Bearer " + getToken() },
  url:
    import.meta.env.VITE_APP_BASE_API +
    "/employeeManagement/employeeManagement/importData",
});
// 添加格式化函数
function formatGender(gender) {
  // 处理直接存储的字符串值
  if (["男", "女"].includes(gender)) {
    return gender;
  }

  // 处理数字代码
  const genderMap = {
    0: "男",
    1: "女",
  };

  return genderMap[String(gender)] || gender;
}

// 根据部门ID获取部门名称
function getDeptNameById(deptId) {
  if (!deptId && deptId !== 0) {
    return "";
  }

  // 转换为数字进行比较，确保类型一致
  const targetDeptId = Number(deptId);

  // 优先从表单部门选项中查找
  if (deptOptions.value && deptOptions.value.length > 0) {
    const dept = deptOptions.value.find(
      (d) => Number(d.deptId) === targetDeptId
    );
    if (dept) {
      return dept.deptName;
    }
  }

  // 从查询条件部门列表中查找
  if (sys_dept_list.value && sys_dept_list.value.length > 0) {
    const dept = sys_dept_list.value.find(
      (d) => Number(d.deptId) === targetDeptId
    );
    if (dept) {
      return dept.deptName;
    }
  }

  return "";
}
const data = reactive({
  form: {}, //用于存储添加或编辑员工时的表单字段值
  queryParams: {
    //用于存储搜索员工列表时的查询条件
    pageNum: 1,
    pageSize: 10,
    empName: null,
    deptName: null,
    phone: null,
  },
  rules: {
    empNo: [{ required: true, message: "员工编号不能为空", trigger: "blur" }],
    empName: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
    gender: [
      // 添加性别必填验证
      { required: true, message: "性别不能为空", trigger: "change" },
    ],
    deptId: [
      // 添加部门必填验证
      { required: true, message: "部门不能为空", trigger: "change" },
    ],
    deptName: [
      // 修改这里，从 deptId 改为 deptName
      { required: true, message: "部门不能为空", trigger: "change" },
    ],
    email: [
      { required: true, message: "电子邮箱不能为空", trigger: "blur" },
      {
        pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
        message: "请输入正确的电子邮箱格式",
        trigger: "blur",
      },
    ],
    phone: [
      { required: true, message: "联系电话不能为空", trigger: "blur" },
      {
        pattern: /^1[3-9]\d{9}$/,
        message: "请输入正确的手机号码格式",
        trigger: "blur",
      },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

function getDeptList() {
  return listDept()
    .then((response) => {
      // 修改部门列表数据结构，使label为部门名称，value为部门名称（而不是部门ID）
      sys_dept_list.value = response.data.map((item) => ({
        deptName: item.deptName, // 部门名称作为显示文本
        deptId: item.deptId, // 部门ID作为值
      }));
    })
    .catch((error) => {
      console.error("获取部门列表失败:", error);
      proxy.$modal.msgError("获取部门列表失败");
      throw error;
    });
}
function getFormDeptList() {
  return listDept()
    .then((response) => {
      // 表单中的部门选项数据结构
      deptOptions.value = response.data;
    })
    .catch((error) => {
      console.error("获取部门列表失败:", error);
      proxy.$modal.msgError("获取部门列表失败");
      throw error;
    });
}
/** 查询培训人员管理列表 */
function getList() {
  loading.value = true;
  listEmployeeManagement(queryParams.value).then((response) => {
    // 直接使用返回的数据，部门名称通过模板中的getDeptNameById函数处理
    employeeManagementList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 恢复跨页选中状态
function restoreSelection() {
  // 这里需要通过 Element Plus 的表格方法恢复选中状态
  // 在模板中添加 ref 后可以使用
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    empNo: null,
    empName: null,
    gender: null,
    deptId: null,
    phone: null,
    email: null,
    deptName: null,
  };
  proxy.resetForm("employeeManagementRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.deptId = null;
  handleQuery();
}

// 多选框选中数据 - 跨页选中核心逻辑
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getFormDeptList(); // 确保获取最新的部门列表
  open.value = true;
  title.value = "添加培训人员管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  getFormDeptList();
  const _id = row.id || ids.value;
  // getEmployeeManagement(_id).then((response) => {
  //   console.log("响应数据为：", response);
  //   form.value = response.data;
  //   open.value = true;
  //   title.value = "修改培训人员管理";
  // });
  getEmployeeManagement(_id).then((response) => {
    console.log("响应数据为：", response);
    // 直接使用返回的 deptName
    form.value = { ...response.data };
    open.value = true;
    title.value = "修改培训人员管理";
  });
}
/** 提交按钮 */
/** 提交按钮 */
function submitForm() {
  proxy.$refs["employeeManagementRef"].validate((valid) => {
    if (valid) {
      // 创建提交数据的副本
      const submitData = { ...form.value };

      // 如果使用 deptName，需要转换为 deptId
      if (submitData.deptName) {
        const dept = deptOptions.value.find(
          (d) => d.deptName === submitData.deptName
        );
        if (dept) {
          submitData.deptId = dept.deptId;
        }
      }

      if (submitData.id != null) {
        updateEmployeeManagement(submitData).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addEmployeeManagement(submitData).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 - 支持跨页删除 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  // 获取要删除的员工姓名用于提示
  const employeeNames =
    row.empName ||
    (Array.isArray(ids.value) && ids.value.length > 0
      ? employeeManagementList.value
          .filter((item) => ids.value.includes(item.id))
          .map((item) => item.empName)
          .join(", ")
      : "");

  // 构建删除确认提示信息
  const confirmMessage = employeeNames
    ? `是否确认删除员工"${employeeNames}"的信息？`
    : `是否确认删除培训人员管理编号为"${_ids}"的数据项？`;

  proxy.$modal
    .confirm(confirmMessage)
    .then(function () {
      // 修复删除功能：确保传递给后端的是字符串格式的ID
      const deleteIds = Array.isArray(_ids) ? _ids.join(",") : _ids;
      return delEmployeeManagement(deleteIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 - 支持跨页导出 */
function handleExport() {
  proxy.download(
    "employeeManagement/employeeManagement/export",
    {
      ...queryParams.value,
    },
    `employeeManagement_${new Date().getTime()}.xlsx`
  );
}
// 导入按钮点击事件
function handleImport() {
  upload.title = "员工导入";
  upload.updateSupport = false;
  upload.isUploading = false;
  proxy.$refs.uploadRef?.clearFiles();
  upload.open = true;
}

// 下载导入模板
function importTemplate() {
  downloadImportTemplate()
    .then((response) => {
      saveAs(response, `employee_template_${new Date().getTime()}.xlsx`);
    })
    .catch(() => {
      proxy.$modal.msgError("模板下载失败");
    });
}

// 文件上传进度处理
function handleFileUploadProgress() {
  upload.isUploading = true;
}

// 文件上传成功处理
function handleFileSuccess(response) {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs.uploadRef?.handleRemove();
  proxy.$alert(
    `<div style="overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;">${response.msg}</div>`,
    "导入结果",
    { dangerouslyUseHTMLString: true }
  );
  getList();
}

// 提交文件表单
function submitFileForm() {
  proxy.$refs.uploadRef?.submit();
}

// 保存文件的通用方法
function saveAs(response, fileName) {
  const blob = new Blob([response]);
  const link = document.createElement("a");
  link.href = URL.createObjectURL(blob);
  link.download = fileName;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}
// 确保先获取部门列表，再获取员工列表
Promise.all([
  getDeptList(), // 用于查询条件的部门列表
  getFormDeptList(), // 用于表单的部门列表
])
  .then(() => {
    getList(); // 部门列表加载完成后再获取员工列表
  })
  .catch(() => {
    getList(); // 即使部门列表加载失败，也要加载员工列表
  });
</script>
